package org.sean.framework.redis;

import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.nio.charset.StandardCharsets;

/**
 * 使用Fastjson处理的 Redis编码类
 * Date: 2018/10/1 17:50
 *
 * @author Sean.xie
 */
public class GzipRedisSerializer implements RedisSerializer<Object> {

    private static final ParserConfig DEFAULT_REDIS_CONFIG = new ParserConfig();

    static {
        DEFAULT_REDIS_CONFIG.setAutoTypeSupport(true);
    }

    /**
     * Creates a new {@link GzipRedisSerializer}
     */
    public GzipRedisSerializer() {
    }


    /**
     * 解码
     */
    @Override
    public Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        return JSON.parseObject(ZipUtil.unGzip(bytes, StandardCharsets.UTF_8.name()),
                null, DEFAULT_REDIS_CONFIG);
    }

    /**
     * 编码
     */
    @Override
    public byte[] serialize(Object t) {
        if (t == null) {
            return new byte[0];
        }
        if (t instanceof byte[]) {
            return (byte[]) t;
        }
        try {
            return ZipUtil.gzip(JSON.toJSONString(t, SerializerFeature.WriteClassName)
                    .getBytes(StandardCharsets.UTF_8.name()));
        } catch (Exception e) {
            // do nothing
            return new byte[0];
        }
    }

}
